package com.hag.equipment_server.netty.server;

import com.hag.equipment_server.util.RedisUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

@Slf4j
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private static NettyServerHandler nettyServerHandler;

    @PostConstruct
    public void init(){
        nettyServerHandler = this;
    }

    @Autowired
    RedisUtils redisUtils;
    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel active......");
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message)msg;
        Data data = message.toData();
        ByteBuf all = message.getAll();

//        log.info(ByteBufToString(all));
        log.info(data.toString());
        nettyServerHandler.redisUtils.set(data.getType(),data.getData());

        if(data.getBreaking()!=null){
            if(data.getType().indexOf("optical1") !=-1) {
                nettyServerHandler.redisUtils.set("break1", data.getBreaking());
            }else{
                nettyServerHandler.redisUtils.set("break2", data.getBreaking());
            }
        }
        if(data.getDifference()!=null){
            if(data.getType().indexOf("optical2") !=-1) {
                nettyServerHandler.redisUtils.set("difference1", data.getDifference());
            }else{
                nettyServerHandler.redisUtils.set("difference2", data.getDifference());
            }
        }



//        log.info("服务器收到消息: {}", msg);
//        ByteBuf buf = (ByteBuf) msg;
//        log.info(buf.readableBytes()+"");
//
//        StringBuilder sb = new StringBuilder();
//
//        //读第几个 默认第一个 i = 1
//        int i = 1;
//        while(buf.isReadable()){
//
//            Byte b = buf.readByte();
//            String hex = this.byteToHex(b);
//
//            if(i == 1){
//                if(hex!="aa"){
//
//                }
//            }
//
//            sb.append(hex);
//            sb.append(",");
//            i++;
//        }
//
//        log.info(sb.toString());
    }

    public String ByteBufToString(ByteBuf buf){
        StringBuilder sb = new StringBuilder();

        //读第几个 默认第一个 i = 1
        int i = 1;
        buf.resetReaderIndex();
        while(buf.isReadable()){
            Byte b = buf.readByte();
            String hex = this.byteToHex(b);

            if(i == 1){
                if(hex!="aa"){

                }
            }

            sb.append(hex);
            sb.append(",");
            i++;
        }
        return sb.toString();
    }

    public int byteToInteger(Byte b) {
        return 0xff & b;
    }

    public String intToHex(int n) {
        final  String[] hexArray = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        if (n < 0) {
            n = n + 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexArray[d1] + hexArray[d2];
    }

    public String byteToHex(Byte b){
        return this.intToHex(this.byteToInteger(b));
    }

    public byte[] toByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }


    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}